// App Root
var appPath = getAppPath();

// 是否延迟加载
var lazy = false;

// Datagrid ID
var datagrid_id = "#advGrid";

// Datagrid URL参数
var datagrid_url = appPath+'/advertising/adv_list.do';

// Dialog ID
var dialog_id = "#addAdvDlg";

// Form ID
var form_id = "#addAdvForm";

// 图片服务器地址
var images1Path = "http://www.hs568.cn";

/**
 * jQuery加载事件
 */
$(function(){
	// 初始化Datagrid
	initPlugin();
	
	// 初始化上传控件
	initCommonUpload();
});

/**
 * 控件初始化方法
 */
function initPlugin() {
	$(datagrid_id).datagrid({
		url: lazy? '' : datagrid_url,
		height: "full",
		striped: true,
		remoteSort:false,
		queryParams: getQueryParam(),
		idField:'adId',
		checkbox:true,
		frozenColumns:[[
		      {field:'ck',checkbox:true},
		      {field:'adId',title:'操作',width:40,align:'center',
		    	  formatter:function(value,rowData,rowIndex){
		    	  	  // var dataStr = JSON.stringify(rowData);
		    		  return "<a href='javascript:void(0)'><img border='0' width='12px' height='12px'  src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' onClick='showEdit("+rowIndex+")'/></a>";
		    	  }
		      }
		]],
		columns:[[
		      {field:'title',title:'标题',width:300,align:'left'},
		      {field:'linkUrl',title:'链接地址',width:320,align:'left'},
		      {field:'createTime',title:'创建时间',width:130,align:'left',
		    	  formatter:function(value,rowData){
		    		  return $.DateUtil.format(new Date(value),'yyyy-MM-dd hh:mm:ss');
		    	  }
		      },
		      {field:'updateTime',title:'更新时间',width:130,align:'left',
		    	  formatter:function(value,rowData){
		    		  return $.DateUtil.format(new Date(value),'yyyy-MM-dd hh:mm:ss');
		    	  }
		      }
		 ]],
		 pagination:true,
		 rownumbers:true,
		 onLoadSuccess: function() {
			 uncheckAll(this);
			 changeTipInfo("tommy-cell");
		 },
		 toolbar:[{
				id:'btnadd',
				text:'增加',
				iconCls:'icon-add',
				handler:function(){
					showAdd();
				}
			},'-',{
				id:'btndelMu',
				text:'删除',
				iconCls:'icon-cancel',
				handler:function(){
					var selections = $(datagrid_id).datagrid('getSelections');
					if(selections == null || selections == ''){
						$.messager.alert('提示信息','请选择要删除的数据','info');
						return ;
					}else{
						$.messager.confirm('提示信息','您确定要删除这些记录？',function(r){
							if(r){
								var ids = '';
								for(var i=0;i<selections.length;i++){
									ids += selections[i].adId+',';
								}
								ids = ids.substring(0,ids.lastIndexOf(','));
								
								$.loading(true);
								$.ajax({
									url:appPath+'/advertising/adv_delMulti.do',
									data:{multi_id:ids},
									success:function(data){
										$.loading(false);
										if(data!='ok'){
											$.messager.alert('提示信息','广告有相关联的模块信息，不能删除！','info');
										}else{
											doReload('delete');
										}
									},
									error:function(XMLHttpRequest, textStatus, errorThrown){
										$.loading(false);
										$.messager.alert('提示信息','抱歉，删除未能完成，'+textStatus,'error');
									}
								});		
							}
						});
					}
				}
			}]
	});
	if (lazy)
		$(datagrid_id).datagrid('options').url = datagrid_url;
}

/**
 * 控件展现方法
 */
function showPlugin() {
	if (lazy) {
		initPlugin();
		lazy = false;
	}		
}

/**
 * 展现编辑广告
 * @param {} rowData
 */
function showEdit(rowIndex){
	var rowData = $(datagrid_id).datagrid("getRows")[rowIndex];
	$(form_id).form('clear');
	$(form_id).form('load',rowData);
	
	$("#submitType").val("update");
	$(dialog_id).window({
			title:'编辑广告',
			iconCls:'icon-edit',
			modal: true,
			shadow: true,
			collapsible:false,
			minimizable:false,
			maximizable:false
		});	
	$(dialog_id).window('move',{top:80});
	$(dialog_id).window('open');	
	
	$("#uploadImg").attr("src", images1Path + rowData.imgPath);
	$("#uploadImg").show();
}

/**
 * 提交数据（包括增加，修改）
 */
function doPostData(){
	$("#title").val($.trim($("#title").val()));
	
	if(!$(form_id).form('validate')){
		return ;
	}
	
	var type = $("#submitType").val();
	var typeStr = "";
	if(type == "save"){
		typeStr = "保存";
	}else if(type == "update"){
		typeStr = "更新";
	}
	
	var subData = $(form_id);  
    var adv = subData.serialize();    
	
    if (type == "save") {
    	if ($.trim($("#picId").val()).length < 1) {
    		$.messager.alert('提示信息','请上传广告图片！','info');
    		return;
    	}
    	ajaxPostData(type, adv);
    } else {
    	ajaxPostData(type, adv);
    }
}

function ajaxPostData(type, adv) {
	$.loading(true);
	$.ajax({
		url:appPath+'/advertising/adv_'+type + '.do',
		type:"post",
		data:adv,
		success:function(data){
			$.loading(false);
			if(data == "error"){
				$.messager.alert('提示信息','该广告已存在！','info');
			}else{
				doReload(type);
				closeWindow();
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			$.loading(false);
			$.messager.alert('提示信息','抱歉，'+typeStr+'未能完成，'+textStatus,'error');
		}
	});
}

/**
 * 关闭对话框
 */
function closeWindow(){
	$(dialog_id).window('close');
}

/**
 * 展现增加广告
 */
function showAdd(){
	$("#uploadImg").hide();
	$(form_id).form('clear');
	$("#submitType").val("save");
	$(dialog_id).window({
		title:'增加广告',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$(dialog_id).window('move',{top:80});
	$(dialog_id).window('open');
}

/**
 * 获取请求信息
 * @return {}
 */
function getQueryParam(){
	var submitObject = new Object();
	submitObject.title = $.trim($('#queryTitleId').val());
	return submitObject;
}

/**
 * 查询数据
 */
function doQuery(){
	showPlugin();
	$(datagrid_id).datagrid('unselectAll');
	$(datagrid_id).datagrid('load',getQueryParam());
}

/**
 * 重载grid，取消全选
 */
function doReload(type){
	var ops = $(datagrid_id).datagrid('getPager').pagination("options");
	if(type == "save"){
		var pn = Math.floor(ops.total/ops.pageSize)+1;
		$(datagrid_id).datagrid('getPager').pagination({pageNumber:pn});
		$(datagrid_id).datagrid('options').pageNumber = pn;
	}else if(type == "delete"){
		if($(datagrid_id).datagrid('getRows').length == $(datagrid_id).datagrid('getSelections').length){
			var pn ;
			var pnt = Math.ceil(ops.total/ops.pageSize);
			var pm = ops.pageNumber;
			if(pnt == (pm-1)){
				pn = pnt ;
			}else{
				pn = pm
			}
			$(datagrid_id).datagrid('getPager').pagination({pageNumber:(pn==0?1:pn)});
			$(datagrid_id).datagrid('options').pageNumber = (pn==0?1:pn);
		}
	}
	$(datagrid_id).datagrid('unselectAll');
	$(datagrid_id).datagrid('reload');
}

//**************************************文件上传相关的的*******start***********************************************
/**
 * 初始化上传控件
 */
function initCommonUpload() {
	//$("#divStatus").hide();
	$("#uploadImg").css("display", "none");
	var attach = new Object();
	attach.attachNo = generateNo("adv");
	attach.attachNotes = "";
	attach.attachType = "pic";
	attach.picType = "";
	attach.splitKey = "";//定义图片切割大小
	attach.fileType = "*.jpg;*.gif;*.png;";
	attach.fileCount = "singleSelect"; //singleSelect 表示一次只能选择一个文件上传
	initUpload('adv_','pics/adv',attach);
}

/**
 * 上传成功后触发的事件
 */
function commonSuccessReturn(attachList){
	var len = attachList.length;
	//console.info("=======len:"+len);
	for(var i=0;i<attachList.length;i++){
		//console.info("=========start  print================");
		//console.info("id:"+attachList[i].id);
		//console.info("name:"+attachList[i].attachRealName);
		//console.info("picType:"+attachList[i].picType);
		if(attachList[i].picType==""){
			//$('#picId').val();
			//$('#attachRealName').val();
			$('#picId').val(attachList[i].attachId);
			$('#attachRealName').val(attachList[i].attachRealName);
			var imgPath=images1Path+attachList[i].attachPath;
			$("#uploadImg").css("display", "block");
			$('#uploadImg').attr("src",imgPath);
			
			$("#attachRealName").focus();
		}
	}
}
//**************************************文件上传相关的的*******end***********************************************

